package com.imooc.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.imooc.base.BaseInfoProperties;
import com.imooc.base.RabbitMqConfig;
import com.imooc.entity.bo.VlogBo;
import com.imooc.entity.mo.MessageMO;
import com.imooc.entity.pojo.MyLikedVlog;
import com.imooc.entity.pojo.Vlog;
import com.imooc.entity.vo.VlogResponse;
import com.imooc.entity.vo.VlogVo;
import com.imooc.enums.MessageEnum;
import com.imooc.enums.YesOrNo;
import com.imooc.mapper.FansMapper;
import com.imooc.mapper.VlogMapper;
import com.imooc.service.FansService;
import com.imooc.service.MsgService;
import com.imooc.service.VlogService;
import com.imooc.utils.JsonUtils;
import com.imooc.utils.PagedGridResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.n3r.idworker.Sid;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
@Slf4j
public class VlogServiceImpl extends BaseInfoProperties implements VlogService {
    @Autowired
    private VlogMapper vlogMapper;

    @Autowired

    private FansService fansService;
    @Autowired
    private MsgService msgService;
    @Autowired
    private Sid sid;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    public void publishVlog(VlogBo vlogBo) {
        Vlog vlog = new Vlog();
        BeanUtils.copyProperties(vlogBo, vlog);
        vlog.setId(sid.nextShort());
        vlog.setIsPrivate(YesOrNo.NO.type);
        vlog.setCreatedTime(new Date());
        vlog.setUpdatedTime(new Date());
        vlog.setLikeCounts(0);
        vlog.setCommentsCounts(0);
        vlogMapper.insert(vlog);
    }


    @Override
    public PagedGridResult findIndexList(String userId, String search, Integer page, Integer pageSize) {
        // 开启分页查询
        PageHelper.startPage(page, pageSize);
        List<VlogVo> vlogVoList = vlogMapper.findIndexList(search);
        // 需要一个新的数组 存储vlogvo变化后的值
        List<VlogVo> vlogVos = new ArrayList<>();
        for (VlogVo vlogVo : vlogVoList) {
            String vlogId = vlogVo.getVlogId();
            String vlogerId = vlogVo.getVlogerId();
            // 判断当前用户是否点赞过视频
            if (StringUtils.isNotBlank(userId)) {
                vlogVo.setDoILikeThisVlog(doILikeVlog(userId, vlogId));
            }
            // 判断用户是否关注博主
            if (StringUtils.isNotBlank(userId)) {
                vlogVo.setDoIFollowVloger(fansService.queryDoIFollowVloger(userId, vlogerId));
            }
            vlogVo.setLikeCounts(getVlogBeLikedCounts(vlogId));
            vlogVos.add(vlogVo);
        }
        return setterPagedGrid(vlogVos, page);
    }

    private Integer getVlogBeLikedCounts(String vlogId) {
        String countsStr = redis.get(REDIS_VLOG_BE_LIKED_COUNTS + ":" + vlogId);
        if (StringUtils.isBlank(countsStr)) {
            countsStr = "0";
        }
        return Integer.valueOf(countsStr);
    }

    private boolean doILikeVlog(String myId, String vlogId) {
        log.info("doILikeVlog myId = {}your: {}", myId , vlogId);
        String doILike = redis.get(REDIS_USER_LIKE_VLOG + ":" + myId + ":" + vlogId);
        log.info("doILike = " + doILike);
        boolean isLike = false;
        if (StringUtils.isNotBlank(doILike) && doILike.equalsIgnoreCase("1")) {
            isLike = true;
            log.info("doILike = {}", isLike);
        }
        return isLike;
    }

    @Override
    public VlogVo getVlogDetailById(String userId, String vlogId) {
        List<VlogVo> list = vlogMapper.getVlogDetailById(vlogId);
        log.info("userId:{},vlogId:{}", userId, vlogId);
        if (list != null && list.size() > 0 && !list.isEmpty()) {
            VlogVo vlogVO = list.get(0);
            return setterVO(vlogVO, userId);
        }
        return null;
    }

    private VlogVo setterVO(VlogVo v, String userId) {
        String vlogerId = v.getVlogerId();
        String vlogId = v.getVlogId();

        if (StringUtils.isNotBlank(userId)) {
            // TODO Bug
            log.info("userId:{},vlogerId:{}",userId, vlogerId);
            // 用户是否关注该博主
            boolean doIFollowVloger = fansService.queryDoIFollowVloger(userId, vlogerId);

            log.info("doIFollowVloger = {}", doIFollowVloger);
            v.setDoIFollowVloger(doIFollowVloger);
            // 判断当前用户是否点赞过视频
            v.setDoILikeThisVlog(doILikeVlog(userId, vlogId));
        }

        // 获得当前视频被点赞过的总数
        v.setLikeCounts(getVlogBeLikedCounts(vlogId));

        return v;
    }

    @Override
    public void changeToPrivate(String userId, String vlogId) {
        vlogMapper.changeToPrivate(userId, vlogId);
    }

    @Override
    public void changeToPublic(String userId, String vlogId) {
        vlogMapper.changeToPublic(userId, vlogId);
    }

    @Override
    public PagedGridResult findMyPublicList(String userId, Integer page, Integer pageSize) {
        PageHelper.startPage(page, pageSize);
        List<VlogVo> vlogVos = vlogMapper.findMyPublishList(userId);
        return setterPagedGrid(vlogVos, page);
    }

    @Override
    public PagedGridResult findMyPrivateList(String userId, Integer page, Integer pageSize) {
        PageHelper.startPage(page, pageSize);
        List<VlogVo> vlogVos = vlogMapper.findMyPrivateList(userId);
        return setterPagedGrid(vlogVos, page);
    }

    @Override
    public void likeVlog(String userId, String vlogId) {
        MyLikedVlog myLikedVlog = new MyLikedVlog();
        myLikedVlog.setId(sid.nextShort());
        myLikedVlog.setUserId(userId);
        myLikedVlog.setVlogId(vlogId);
        vlogMapper.saveLikeRel(myLikedVlog);
        // 系统消息: 点赞短视频
        Vlog vlog = this.getVlog(vlogId);
        Map msgContent = new HashMap();
        msgContent.put("vlogId", vlogId);
        msgContent.put("vlogCover", vlog.getCover());
        // mq 异步解耦
//        msgService.createMsg(userId,vlog.getVlogerId(), MessageEnum.LIKE_VLOG.type,msgContent);
        MessageMO messageMO = new MessageMO();
        messageMO.setMsgContent(msgContent);
        messageMO.setFromUserId(userId);
        messageMO.setToUserId(vlog.getVlogerId());

        rabbitTemplate.convertAndSend(RabbitMqConfig.EXCHANGE_NAME, "sys.msg." + MessageEnum.LIKE_VLOG.enValue, JsonUtils.objectToJson(messageMO));
    }

    @Override
    public Vlog getVlog(String vlogId) {
        return vlogMapper.getVlogByVlogId(vlogId);
    }

    @Override
    public void unlikeVlog(String userId, String vlogId) {
        vlogMapper.unLikeRel(userId, vlogId);
        MessageMO messageMO = new MessageMO();
        messageMO.setFromUserId(userId);
        messageMO.setToUserId(vlogId);
        rabbitTemplate.convertAndSend(RabbitMqConfig.EXCHANGE_NAME, "sys.msg." + MessageEnum.UN_LIKE_VLOG, JsonUtils.objectToJson(messageMO));
//        msgService.unlikeThisVlog(userId,vlogId);
    }

    @Override
    public PagedGridResult getMyLikedVlogList(String userId, Integer page, Integer pageSize) {
        PageHelper.startPage(page, pageSize);
        List<VlogVo> myLikedVlogList = vlogMapper.getMyLikedVlogList(userId);
        return setterPagedGrid(myLikedVlogList, page);
    }

    @Override
    public PagedGridResult getMyFollowVlogList(String myId, Integer page, Integer pageSize) {
        PageHelper.startPage(page, pageSize);
        List<VlogVo> vlogVoList = vlogMapper.getMyFollowVlogList(myId);
        log.info("vlogVoList = " + vlogVoList);
        // 需要一个新的数组 存储vlogvo变化后的值
        List<VlogVo> vlogVos = new ArrayList<>();
        for (VlogVo vlogVo : vlogVoList) {
            String vlogId = vlogVo.getVlogId();
            String vlogerId = vlogVo.getVlogerId();
            // 判断当前用户是否点赞过视频
            if (StringUtils.isNotBlank(myId)) {
                vlogVo.setDoIFollowVloger(true);
                vlogVo.setDoILikeThisVlog(doILikeVlog(myId, vlogId));
            }
            vlogVo.setLikeCounts(getVlogBeLikedCounts(vlogId));
            vlogVos.add(vlogVo);
        }
        return setterPagedGrid(vlogVos, page);
    }

    @Override
    public PagedGridResult getFriendVlogList(String myId, Integer page, Integer pageSize) {
        PageHelper.startPage(page, pageSize);
        List<VlogVo> vlogVoList = vlogMapper.getFriendVlogList(myId);
        List<VlogVo> vlogVos = new ArrayList<>();
        for (VlogVo vlogVo : vlogVoList) {
            String vlogId = vlogVo.getVlogId();
            String vlogerId = vlogVo.getVlogerId();
            // 判断当前用户是否点赞过视频
            if (StringUtils.isNotBlank(myId)) {
                vlogVo.setDoIFollowVloger(true);
                vlogVo.setDoILikeThisVlog(doILikeVlog(myId, vlogId));
            }
            vlogVo.setLikeCounts(getVlogBeLikedCounts(vlogId));
            vlogVos.add(vlogVo);
        }
        return setterPagedGrid(vlogVos, page);
    }
}
